<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'asd:ll:asdTmLlH:edit'"
    :show-ok-btn="false"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="95%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdsSelect>
        <ListSelect
          v-model:value="itemCodes"
          :labelValue="itemNames"
          :selectType="selectType"
          :checkbox="true"
          @select="handSelect"
        />
      </template>

      <template #asdTmLlRdsList>
        <BasicTable @register="registerAsdTmLlRdsTable" @row-click="handleAsdTmLlRdsRowClick" />
        <a-button class="mt-2" @click="handleAsdTmLlRdsAdd" v-auth="'asd:ll:asdTmLlH:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button type="primary" :loading="loading" @click="handleSubmit()">
        <Icon icon="ant-design:check-outlined" /> {{ t('确认') }}
      </a-button>
    </template>
  </BasicDrawer>

  <div>
    <PosList @register="registerPosDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsAsdLlAsdTmLlHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { AsdTmLlH, asdTmLlHSaveLl, asdTmLlHForm } from '/@/api/asd/ll/asdTmLlH';
  import { ListSelect } from '/@/components/ListSelect';
  import PosList from './posList.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('asd.ll.asdTmLlH');
  const { showMessage } = useMessage();
  const record = ref<AsdTmLlH>({} as AsdTmLlH);
  let loading = ref(false);
  const itemCodes = ref('');
  const itemNames = ref('');
  const selectType = ref('masterSelect');

  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增领料申请') : t('编辑领料申请'),
  }));

  const [registerPosDrawer, { openDrawer }] = useDrawer();

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('发料仓库'),
      field: 'cwhcode',
      component: 'Select',
      componentProps: {
        dictType: 'ASD_WH',
      },
      required: true,
    },
    {
      label: t('需求仓库'),
      field: 'xqCwhcode',
      component: 'Select',
      componentProps: {
        dictType: 'ASD_WH',
      },
      required: true,
    },
    {
      label: t('选择'),
      field: 'selIds',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdsSelect',
      show: false,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('领料明细'),
      field: 'asdTmLlRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'asdTmLlRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerAsdTmLlRdsTable, asdTmLlRdsTable] = useTable({
    actionColumn: {
      width: 50,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleAsdTmLlRdsDelete.bind(this, record),
          },
          auth: 'asd:ll:asdTmLlH:edit',
          ifShow: record.allowEdit | record.allowDel,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    ellipsis: false,
    size: 'small',
    inset: true,
  });

  async function setAsdTmLlRdsTableData(_res: Recordable) {
    asdTmLlRdsTable.setColumns([
      {
        title: t('Master编码'),
        dataIndex: 'bomcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'basInv.cinvcode',
        key: 'basInv.cinvcode',
        width: 170,
      },
      {
        title: t('存货代码'),
        dataIndex: 'basInv.cinvaddcode',
        key: 'basInv.cinvaddcode',
        width: 170,
        ifShow: false,
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        key: 'basInv.cinvname',
        width: 170,
      },
      {
        title: t('构成比例'),
        dataIndex: 'frate',
        width: 60,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('需求数'),
        dataIndex: 'iqty',
        width: 80,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
          rules: [
            {
              pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
              message: t('请输入一个数值'),
            },
          ],
        },
        editRule: true,
      },
      {
        title: t('区域'),
        dataIndex: 'area',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          options: [
            { label: 'A', value: 'A' },
            { label: 'B', value: 'B' },
            { label: 'C', value: 'C' },
            { label: 'D', value: 'D' },
            { label: '其他', value: '其他' },
          ],
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('需求时间'),
        dataIndex: 'xqDate',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
        },
        editRule: true,
      },
    ]);
    asdTmLlRdsTable.setTableData(record.value.asdTmLlRdsList || []);
  }

  function handleAsdTmLlRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleAsdTmLlRdsAdd() {
    document.getElementById('form_item_selIds')?.click();
  }

  async function handlePosForm(record: Recordable) {
    openDrawer(true, { id: record.id, cinvcode: record.cinvcode, iqty: record.iqty });
  }

  /**
   * 选择
   * @param selectData
   */
  function handSelect(selectData) {
    if (selectType.value === 'masterSelect') {
      selectData.forEach((item) => {
        asdTmLlRdsTable.insertTableDataRecord({
          id: '',
          ...item,
          isNewRecord: true,
          editable: true,
          cinvcode: item.basInv.cinvcode,
          frate: item.unitNumber,
          iqty: item.iqty,
          area: '',
          xqDate: '',
        });
      });
    } else {
      asdTmLlRdsTable.insertTableDataRecord({
        id: new Date().getTime(),
        isNewRecord: true,
        editable: true,
      });
    }
  }

  async function handleSuccess() {
    setDrawerProps({ loading: true });
    const res = await asdTmLlHForm({ djno: record.value.djno });
    record.value = (res.asdTmLlH || {}) as AsdTmLlH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setAsdTmLlRdsTableData(res);
    setDrawerProps({ loading: false });
  }

  function handleAsdTmLlRdsDelete(record: Recordable) {
    asdTmLlRdsTable.deleteTableDataRecord(record);
  }

  async function getAsdTmLlRdsList() {
    let asdTmLlRdsListValid = true;
    let asdTmLlRdsList: Recordable[] = [];
    for (const record of asdTmLlRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        asdTmLlRdsListValid = false;
      }
      asdTmLlRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
        area: record.editValueRefs.area,
        xqDate: record.editValueRefs.xqDate,
      });
    }
    for (const record of asdTmLlRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      asdTmLlRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!asdTmLlRdsListValid) {
      throw { errorFields: [{ name: ['asdTmLlRdsList'] }] };
    }
    return asdTmLlRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await asdTmLlHForm(data);
    record.value = (res.asdTmLlH || {}) as AsdTmLlH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setAsdTmLlRdsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.asdTmLlRdsList = await getAsdTmLlRdsList();
      console.log(data);
      const res = await asdTmLlHSaveLl(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
